package com.study.spaoplog.interceptor;

import com.study.spaoplog.constant.SysConst;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author study
 * @version 1.0
 * @date 2021/6/18 9:35
 */
@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put(SysConst.LOG_MDC_ID, UUID.randomUUID().toString().replace("-", ""));
        //打印接口请求信息
        String method = request.getMethod();
        String uri = request.getRequestURI();
        // log.info("[请求接口] : {} : {}", method, uri);
        return true;
    }

    /**
     * https://www.ngui.cc/51cto/show-665519.html
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        //删除MDC值
        // MDC.remove(SysConst.LOG_MDC_ID);
    }
    /*@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //URL=http://127.0.0.1:9590/error|/error
        log.info("|拦截器|URL={}|{}", request.getRequestURL(), request.getRequestURI());
        //System.out.println("拦截器"+handler);
        //TODO 判断拦截的请求的访问的注解|但是访问静态资源时提示|ResourceHttpRequestHandler cannot be cast to org.springframework.web.method.HandlerMethod
        if (handler instanceof HandlerMethod) {
            HandlerMethod mh = (HandlerMethod) handler;
            LoginRequired loginRequired = mh.getMethodAnnotation(LoginRequired.class);
            if (loginRequired != null) {
                log.error("登录");
            }
        }
        return true;
    }*/
}
